import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

class VideoBase extends StatefulWidget {
  final double height;
  final String videoUrl;
  const VideoBase({super.key, required this.videoUrl, this.height = 220});

  @override
  State<VideoBase> createState() => _VideoBaseState();
}

class _VideoBaseState extends State<VideoBase> {
  late VideoPlayerController _videoController;
  late ChewieController _chewieController;
  bool videoInitialized = false;

  @override
  void initState() {
    super.initState();
    _videoController =
        VideoPlayerController.networkUrl(Uri.parse(widget.videoUrl));
    initializeVideo(widget.videoUrl);
  }

  @override
  void didUpdateWidget(VideoBase oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.videoUrl != widget.videoUrl) {
      initializeVideo(widget.videoUrl);
    }
  }

  void initializeVideo(String videoUrl) {
    if (videoInitialized) {
      _videoController.dispose();
      _chewieController.dispose();
      setState(() => videoInitialized = false);
    }

    _videoController = VideoPlayerController.networkUrl(Uri.parse(videoUrl));
    _videoController.initialize().then((_) {
      setState(() {
        _chewieController = ChewieController(
          videoPlayerController: _videoController,
          aspectRatio: _videoController.value.aspectRatio,
          autoPlay: true,
          looping: true,
          showControlsOnInitialize: false,
          hideControlsTimer: const Duration(milliseconds: 1500),
          allowFullScreen: true,
          autoInitialize: true,
          placeholder: const Center(child: CircularProgressIndicator()),
          errorBuilder: (context, errorMessage) =>
              Center(child: Text(errorMessage)),
          optionsTranslation: OptionsTranslation(
            playbackSpeedButtonText: '播放速度',
            subtitlesButtonText: '字幕',
            cancelButtonText: '取消',
          ),
          // 不再使用自定义控件，而是使用 Chewie 的默认控件
        );
        videoInitialized = true;
      });
    });
  }

  @override
  void dispose() {
    _videoController.dispose();
    _chewieController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.black,
      height: widget.height,
      child: videoInitialized
          ? GestureDetector(
              behavior: HitTestBehavior.translucent, // 允许穿透手势
              onTap: () {
                // 单击切换控制栏显示
              },
              onDoubleTap: () {
                // 双击切换播放/暂停
                if (_chewieController.isPlaying) {
                  _chewieController.pause();
                } else {
                  _chewieController.play();
                }
              },
              child: Chewie(
                controller: _chewieController,
              ),
            )
          : const Center(child: CircularProgressIndicator()),
    );
  }
}
